import sqlite3
from datetime import datetime

class GameRecord:
    def __init__(self):
        self.conn = sqlite3.connect('game_records.db')
        self.create_table()
    
    def create_table(self):
        cursor = self.conn.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS game_records (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                final_mood INTEGER NOT NULL,
                result TEXT NOT NULL,
                duration INTEGER NOT NULL,
                actions_taken TEXT NOT NULL
            )
        ''')
        self.conn.commit()
    
    def add_record(self, final_mood, result, duration, actions):
        """
        添加一条游戏记录
        :param final_mood: 最终心情值
        :param result: 游戏结果 ('胜利'/'失败'/'中途退出')
        :param duration: 游戏持续时间(秒)
        :param actions: 采取的行动列表
        """
        cursor = self.conn.cursor()
        current_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        actions_str = ','.join(actions)
        
        cursor.execute('''
            INSERT INTO game_records (date, final_mood, result, duration, actions_taken)
            VALUES (?, ?, ?, ?, ?)
        ''', (current_date, final_mood, result, duration, actions_str))
        self.conn.commit()
    
    def get_all_records(self):
        """获取所有游戏记录"""
        cursor = self.conn.cursor()
        cursor.execute('SELECT * FROM game_records ORDER BY date DESC')
        return cursor.fetchall()
    
    def get_statistics(self):
        """获取游戏统计数据"""
        cursor = self.conn.cursor()
        stats = {}
        
        # 总游戏次数
        cursor.execute('SELECT COUNT(*) FROM game_records')
        stats['total_games'] = cursor.fetchone()[0]
        
        # 胜利次数
        cursor.execute('SELECT COUNT(*) FROM game_records WHERE result = "胜利"')
        stats['wins'] = cursor.fetchone()[0]
        
        # 平均心情值
        cursor.execute('SELECT AVG(final_mood) FROM game_records')
        stats['avg_mood'] = round(cursor.fetchone()[0] or 0, 2)
        
        # 最常使用的行动
        cursor.execute('SELECT actions_taken FROM game_records')
        all_actions = cursor.fetchall()
        action_count = {}
        for actions in all_actions:
            for action in actions[0].split(','):
                action_count[action] = action_count.get(action, 0) + 1
        
        if action_count:
            stats['most_used_action'] = max(action_count.items(), key=lambda x: x[1])[0]
        else:
            stats['most_used_action'] = "无"
        
        return stats
    
    def clear_records(self):
        """清空所有记录"""
        cursor = self.conn.cursor()
        cursor.execute('DELETE FROM game_records')
        self.conn.commit()
    
    def close(self):
        """关闭数据库连接"""
        self.conn.close()

# 使用示例
if __name__ == '__main__':
    # 创建记录工具实例
    record = GameRecord()
    
    # 添加测试记录
    record.add_record(
        final_mood=85,
        result='胜利',
        duration=300,
        actions=['送花', '讲笑话', '拥抱']
    )
    
    # 获取统计数据
    stats = record.get_statistics()
    print("游戏统计：")
    print(f"总游戏次数：{stats['total_games']}")
    print(f"胜利次数：{stats['wins']}")
    print(f"平均心情值：{stats['avg_mood']}")
    print(f"最常使用的行动：{stats['most_used_action']}")
    
    # 获取所有记录
    records = record.get_all_records()
    print("\n游戏记录：")
    for record in records:
        print(f"日期：{record[1]}")
        print(f"最终心情值：{record[2]}")
        print(f"结果：{record[3]}")
        print(f"持续时间：{record[4]}秒")
        print(f"采取的行动：{record[5]}")
        print("-" * 30)
    
    # 关闭数据库连接
    record.close()